package cn.yanhu.kuwanapp.utils.helper

import android.annotation.SuppressLint
import android.content.Context
import android.net.http.SslError
import android.os.Build
import android.webkit.*
import cn.woochen.comlib.util.ApplicationUtil
import cn.woochen.comlib.util.PackageUtil
import cn.woochen.comlib.util.UserPref
import cn.yanhu.kuwanapp.http.UrlConstainer
import cn.yanhu.kuwanapp.utils.ChannelUtils
import cn.yanhu.kuwanapp.utils.MainJavascriptInterface
import cn.yanhu.kuwanapp.utils.constans.Constants
import cn.yanhu.kuwanapp.utils.ext.logcom
import java.lang.reflect.InvocationTargetException

/**
 *
 * 类描述：
 * @author：woochen
 * create at：2021/7/31 6:47 AM
 */
object WebViewHelper {

    private var mToken by UserPref(Constants.USER_TOKEN, "")

    private  fun headers():HashMap<String,String>{
        return hashMapOf<String,String>("packagename" to ApplicationUtil.context.packageName)
    }

    /**
     * 加载url
     *
     */
    fun loadUrl(webView: WebView,url:String){
        webView.loadUrl(url, headers())
    }

    /**
     * 配置设置
     * @param webView WebView
     */
    @SuppressLint("JavascriptInterface")
    fun configSetting(context: Context,webView: WebView,pageLoadFinish:()->Unit = {},receiveTitle:(String)->Unit={}){
        webView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                if (url == null) return true
                if (url.startsWith("http") || url.startsWith("https")) {
                    view?.loadUrl(url)
                    return true
                } else {
                    return true
                }
            }

            override fun onLoadResource(view: WebView?, url: String?) {
                super.onLoadResource(view, url)
                logcom("资源加载：$url")
            }

            override fun onPageFinished(view: WebView, url: String) {
                super.onPageFinished(view, url)
                webView.settings.blockNetworkImage = false
                pageLoadFinish.invoke()
                saveDataToLocalStorage(webView,"appVersion", PackageUtil.getCurrentVersionName(ApplicationUtil.context))
                saveDataToLocalStorage(webView,"packageName", ApplicationUtil.context.packageName)
                saveDataToLocalStorage(webView,"os", "1")
                saveDataToLocalStorage(webView,"token", mToken)
                saveDataToLocalStorage(webView,"channel", ChannelUtils.getChannel())
            }

            override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
                handler?.proceed()
            }
        }
        val webSettings = webView.settings
        webSettings.javaScriptEnabled = true
        webSettings.javaScriptCanOpenWindowsAutomatically = true
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }
        //跨域问题
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            webView.settings.allowUniversalAccessFromFileURLs = true
        } else {
            try {
                val clazz = webView.settings::class.java
                val method =
                    clazz.getMethod("setAllowUniversalAccessFromFileURLs", Boolean::class.javaPrimitiveType)
                method.invoke(webView.settings, true)
            } catch (e: NoSuchMethodException) {
                e.printStackTrace()
            } catch (e: InvocationTargetException) {
                e.printStackTrace()
            } catch (e: IllegalAccessException) {
                e.printStackTrace()
            }

        }
        // 支持缩放(适配到当前屏幕)
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { //少于4.4（不包括4.4）用这个
            webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        }
        //适应屏幕，大于等于4.4用这个
        webSettings.useWideViewPort = true
        webSettings.domStorageEnabled = true
        webSettings.javaScriptCanOpenWindowsAutomatically = true
        webSettings.loadWithOverviewMode = true
        webSettings.setSupportZoom(true)
        webSettings.blockNetworkImage = true
        webSettings.domStorageEnabled = true
        webSettings.cacheMode = WebSettings.LOAD_DEFAULT
        webView.addJavascriptInterface(MainJavascriptInterface(context, hashMapOf()), "android")
        webView.webChromeClient = object : WebChromeClient() {

            override fun onReceivedTitle(view: WebView, title: String) {
                receiveTitle.invoke(title)
            }

            override fun onJsAlert(view: WebView?, url: String?, message: String?, result: JsResult?): Boolean {
                return super.onJsAlert(view, url, message, result)
            }
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(UrlConstainer.SHOW_LOG)
        }
    }

    /**
     * 保存数据到localStorage
     */
    fun saveDataToLocalStorage(webView: WebView,key: String, value: String) {
        val js = "window.localStorage.setItem('${key}','$value');"
        val jsUrl = "javascript:(function({window.localStorage.setItem('${key}','$value')})()"
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
           webView.evaluateJavascript(js, null);
        } else {
            webView.loadUrl(jsUrl)
            webView.reload()
        }
    }
}